//
//  CallHisViewController.m
//  DS爱信
//
//  Created by 秦建英 on 14-6-9.
//  Copyright (c) 2014年 秦建英. All rights reserved.
//

#import "CallHisViewController.h"
#import "DSViewController.h"
#import "DSDengViewController.h"
#import "NetAccess.h"
#import "Header.h"
#import "SecurityUtil.h"
#import "Reachability.h"
#import "NSString+Hashing.h"
#import <AVFoundation/AVFoundation.h>
@implementation CallHisViewController
{
    UILabel *_label1;
    UILabel *_label;
    UILabel *_label2;
    NSMutableData *_data;
    NSUserDefaults *users;
    NSString *_date;
    NSDate* _dat;
    NSString *_name;
    NSString *_strUrl;
    AVAudioPlayer *_player;
    NSString *_resquestString;
}
- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        _label1 =[[UILabel alloc]initWithFrame:CGRectMake(10, 190, 300, 40)];
        _label2 =[[UILabel alloc]initWithFrame:CGRectMake(10, 240, 300, 40)];
    }
    return self;
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.view .userInteractionEnabled =YES;
    [self.navigationController setNavigationBarHidden:YES animated:animated];
    [self readAllPeoples ];
    [self music];
}
-(void)music
{
    NSString *path =[NSString stringWithFormat:@"%@/callphoneyinpin.mp3",[[NSBundle mainBundle] resourcePath]];
    NSURL *url =[NSURL fileURLWithPath:path];
    _player =[[AVAudioPlayer alloc]initWithContentsOfURL:url error:nil];
    [_player prepareToPlay];
    [_player play];
}
-(void )chg
{
    users =[NSUserDefaults standardUserDefaults];
    NSArray *array =[users objectForKey:@"users"];
    NSDictionary *dict =[array objectAtIndex:0];
    _name =[dict objectForKey:@"username"];
    NSString *str = [[_tellName objectAtIndex:0] stringByReplacingOccurrencesOfString:@"-" withString:@""];
    _strUrl=[str stringByReplacingOccurrencesOfString:@" " withString:@""];
    NetAccess*net = [NetAccess sharedNetAccess];
    if(![net haveNet])
    {
        NSLog(@"网络不可用");
        //没有网络
        UIAlertView *alertView=[[UIAlertView alloc]initWithTitle:@"提示" message:@"无网络连接" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alertView show];
    }else{
        _resquestString =[NSString stringWithFormat:@"http://182.92.157.109/api/mapp/call.aspx?a=%@&b=%@&c=1",_name,_strUrl];
        NSString *hh =[SecurityUtil encodeBase64String:_resquestString];
        NSString *df=[SecurityUtil encodeBase64String:hh];
        NSData *aesData = [SecurityUtil encryptAESData:df];
        NSString *dd= [SecurityUtil decryptAESData:aesData];
        NSLog(@"%@", [SecurityUtil decodeBase64String:dd]);
        NSLog(@"%@",[SecurityUtil decodeBase64String:[SecurityUtil decodeBase64String:dd]]);
        NSURL *url =[NSURL URLWithString:[SecurityUtil decodeBase64String:[SecurityUtil decodeBase64String:dd]]];
        NSURLRequest *request =[NSURLRequest requestWithURL:url];
        NSURLConnection *connect =[[NSURLConnection alloc]initWithRequest:request delegate:self];
        [connect start];
    }
}
-(void)readAllPeoples
{
    if(DeviceHeight==568)
    {
        UIImage *imaged =[UIImage imageNamed:@"call_living3@2x.png"];
        UIImageView *imh =[[UIImageView alloc]initWithFrame:self.view.bounds];
        imh.image =imaged;
        [self.view addSubview:imh];
    }else{
        self.view.backgroundColor =[UIColor colorWithPatternImage:[UIImage imageNamed:@"call_living3@2x.png"]];
    }
    _label2.text =[NSString stringWithFormat:@"%@",[_tellName objectAtIndex:1]];
    _label2.font =[UIFont fontWithName:@"Arial Rounded MT Bold" size:25];
    _label2.backgroundColor =[UIColor clearColor];
    _label2.textAlignment =NSTextAlignmentCenter;
    [self.view addSubview:_label2];
    
    _label1.text =[NSString stringWithFormat:@"%@",[_tellName objectAtIndex:0]];
    _label1.font =[UIFont fontWithName:@"Arial Rounded MT Bold" size:25];
    _label1.backgroundColor =[UIColor clearColor];
    _label1.textAlignment =NSTextAlignmentCenter;
    [self.view addSubview:_label1];
    UIImageView *imageView =[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"call_living_p@2x.jpg"]];
    imageView.frame =CGRectMake(110, 70, 100, 100);
    [self.view addSubview:imageView];
    
    UIButton *btn =[UIButton buttonWithType:UIButtonTypeRoundedRect];
    btn.backgroundColor =[UIColor colorWithRed:1.0f green:0.10f blue:0.03f alpha:1];
    btn.layer.cornerRadius =10;
    btn.frame =CGRectMake(10, _label1.frame.origin.y+150, 300, 40);
    [btn addTarget:self action:@selector(btnClick) forControlEvents:UIControlEventTouchUpInside];
    UIImageView *image =[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"ic_end_call.png"]];
    image.frame =CGRectMake(130, 6, 35, 30);
    [self.view addSubview:btn];
    [btn addSubview:image];
    _label =[[UILabel alloc]initWithFrame:CGRectMake(10,30, 300, 40)];
    _label.backgroundColor =[UIColor clearColor];
    _label.font =[UIFont fontWithName:@"Arial Rounded MT Bold" size:15];
    _label.textAlignment =NSTextAlignmentCenter;
    [self.view addSubview:_label];
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    [[UIDevice currentDevice] setProximityMonitoringEnabled:YES];
    [self chg];
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    _data =[[NSMutableData alloc]init];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [_data appendData:data];
}
+(NSString *)pathWithurlString:(NSString *)str
{
    return [NSHomeDirectory() stringByAppendingFormat:@"/Documents/%@",[str MD5Hash]];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSString *path =[CallHisViewController pathWithurlString:_resquestString];
    [_data writeToFile:path atomically:YES];
    NSString * sd =[[NSString alloc]initWithData:_data encoding:NSUTF8StringEncoding];
    NSLog(@"即将 ===== %@",sd);
    if([sd hasPrefix:@"0|1"]){
        _label.text =@"正在接通中,请稍后..";
        [self performSelectorInBackground:@selector(get) withObject:self];
    }else
    {
        NSArray *listItems = [sd componentsSeparatedByString:@"|"];
        _label.text =[NSString stringWithFormat:@"%@",[listItems objectAtIndex:3]];
    }
}
-(void)get
{
    if ([[UIDevice currentDevice] proximityState] == NO)
    {
        [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
    }
    sleep(8);
    [_player pause];
    [NSThread detachNewThreadSelector:@selector(inty) toTarget:self withObject:nil];
}
-(void)inty
{
    sleep(12);
    [self btnClick];
}
-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [_player pause];
    [[UIDevice currentDevice] setProximityMonitoringEnabled:NO];
    [self.view removeFromSuperview];
}
-(void)btnClick
{
    UIViewController *controller=[[DSViewController alloc]init];
    [self presentModalViewController:controller animated:YES];

}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}
@end